<template>
  <Modal :modelValue="modelValue" :title="title" @close="handleCloseDialog" @open="handleOpenDialog" width="635px"
    maxHeight="auto">
    <el-form ref="permissionFormRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="别名" prop="alias">
        <el-input v-model="form.alias" placeholder="请输别名" />
      </el-form-item>
      <el-form-item label="微服务ID" prop="service_id">
        <el-input v-model="form.service_id" placeholder="请输微服务ID" />
      </el-form-item>
      <el-form-item label="路径模式" prop="api_pattern">
        <el-input v-model="form.api_pattern" placeholder="请输路径模式" />
      </el-form-item>
      <el-form-item label="请求方法" prop="api_method">
        <el-input v-model="form.api_method" placeholder="请输请求方法" />
      </el-form-item>
      <el-form-item label="授权方式" prop="api_bypass">
        <el-select v-model="form.api_bypass">
          <el-option label="授权" value="permitted" />
          <el-option label="登录" value="user" />
          <el-option label="匿名" value="anonymous" />
        </el-select>
      </el-form-item>
      <el-form-item label="上级类目" prop="pid">
        <el-tree-select v-model="form.pid" placeholder="选择上级类目" :data="parentPermissionData" filterable check-strictly
          :props="{ children: 'children', label: 'name', value: 'id' }" :render-after-expand="false" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="modal-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading" :disabled="loading"> 确 定 </el-button>
        <el-button @click="handleCloseDialog"> 取 消 </el-button>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
defineOptions({
  name: "Permission",
  inheritAttrs: false,
})
import PermissionAPI, { PermissionVO, PermissionForm } from "@/api/permission"
import { buildTreeSelect } from "@/utils";

// 定义接收的属性
interface Props {
  modelValue: boolean
  permissionItem?: PermissionVO
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '表单',
})

// 自定义事件
const emit = defineEmits<{
  submit: [form: PermissionForm]
  close: []
}>()

const permissionFormRef = ref(ElForm)

const loading = ref(false)

const parentPermissionData = ref<PermissionVO[]>()

// 初始表单数据
const initialPermissionForm = ref<PermissionForm>({
  pid: 0,
})

const form = ref<PermissionForm>({ ...initialPermissionForm.value })

const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  alias: [{ required: true, message: "别名不能为空", trigger: "blur" }],
})

/**
 * 打开部门弹窗
 */
const handleOpenDialog = async () => {

}

/** 提交部门表单 */
const handleSubmit = () => {
  permissionFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true
      if (form.value.id) {
        updateData()
      } else {
        saveData()
      }
    }
  })
}

const saveData = () => {
  loading.value = true
  PermissionAPI.add(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}

const updateData = () => {
  loading.value = true
  PermissionAPI.update(form.value).then((res) => {
    if (res.status === 200) {
      ElMessage.success("新增成功")
      emit('submit', res.data)
    }
  }).finally(() => { loading.value = false })
}
/** 关闭弹窗 */
const handleCloseDialog = () => {
  if (permissionFormRef.value) {
    permissionFormRef.value.resetFields()
    permissionFormRef.value.clearValidate()
  }
  form.value = Object.assign({}, initialPermissionForm.value)
  emit('close')
}

const getPermissionTree = async () => {
  // 加载部门下拉数据
  PermissionAPI.query().then(res => {
    if (res.status === 200) {
      const data = buildTreeSelect(res.data, 'id', 'pid', 'id', 'name')
      parentPermissionData.value = [
        {
          id: 0,
          name: "顶级类目",
          children: data,
        },
      ]
    }
  })
}

const getFormData = (permissionId: number) => {
  PermissionAPI.getFormData(permissionId).then(res => {
    if (res.status === 200) {
      form.value = Object.assign({}, res.data)
    }
  })
}

//表单传递数据
watch(() => props.permissionItem, (newVal: any, oldVal) => {
  if (newVal) {
    form.value = Object.assign({}, newVal)
    if (newVal.permission_id) {
      getFormData(newVal.permission_id)
    }
  }
  getPermissionTree()

}, { immediate: true, deep: true })

</script>
